package com.bayair.doctor.net;

import com.bayair.doctor.net.exception.DataException;
import com.bayair.doctor.net.exception.ServerException;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;


/**
    返回数据格式：解析到 data{..}中的code
 * {
 *  "code": 0,
 *  "msg": "success",
 *  "data": {
 *      "code": 0,
 *      "newtoken": "b5ce326942cf644f8705e0e21e75ff13",
 *      "imname": "doctorhuang",
 *      "expire": 1576312419
 *      }
 *  }
 */
public class RxFunction<T> implements Function<BaseEntity<T>, T> {

    @Override
    public T apply(@NonNull BaseEntity<T> t) throws IOException {
        if (!t.isSuccess()) {
            throw new ServerException(t.getCode());
        }
        T data = t.getData();
        if (data != null) {
            try {
                String dataJsonStr = new Gson().toJson(data);
                JSONObject object = new JSONObject(dataJsonStr);
                int code = object.optInt("code");
                if (code == 0) {
                    return data;
                } else {
                    throw new DataException(code);
                }
            } catch (JSONException e) {
                throw new DataException(DataException.ERROR.OTHER_ERROR, "data格式返回错误");
            }
        }
        return data;
    }
}
